package main

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/go-redis/redis/v7"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"github.com/nsqio/go-nsq"
	"go-web/model"
	"io"
	"log"
	"math/rand"
	"os"
	"time"
)

var db *gorm.DB
var Redis *redis.Client
var mq *nsq.Producer

func init() {
	conn := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=True&loc=Local&timeout=10s",
		"admin123",
		"Lingmaimai001",
		"mysql8.rwlb.rds.aliyuncs.com:3306",
		"test",
	)

	var err error
	if db, err = gorm.Open("mysql", conn); err != nil {
		log.Fatalf("Fail to connect db : %v", err)
	}

	//defer DB.Close()

	db.LogMode(true)
	//默认加s， grom转义struct名字的时候不用加上s
	//db.SingularTable(true)


	// idle 空闲的
	db.DB().SetMaxIdleConns(40)
	db.DB().SetMaxOpenConns(40)


	Redis = redis.NewClient(&redis.Options{
		Addr:     "bjdxt.qcgameweb02.qiyi.redis:6521",
		Password: "uWu630F4DGfj",
		DB:       0,
	})

	pong, err := Redis.Ping().Result()
	fmt.Println(pong, err)

	fields := make(map[string]interface{})
	fields["id"] = 1
	fields["stock"] = 10000
	err = Redis.HMSet("goods:1", fields).Err()

	if err != nil {
		panic(err)
	}


	conn = "39.100.58.10:4150"
	config := nsq.NewConfig()
	mq, err = nsq.NewProducer(conn, config)
	if err != nil {
		log.Panic(err)
	}
}


func main() {

	rand.Seed(time.Now().UnixNano())

	gin.SetMode(gin.ReleaseMode)
	f, _ := os.Create("gin.log")
	gin.DefaultWriter = io.MultiWriter(f)

	r := gin.Default()
	r.GET("/order", func(c *gin.Context) {
		order()
		c.JSON(200, gin.H{
			"message": "sale",
		})
	})

	r.Run()
}

func order() {

	goodsId := 1
	var number int64 = 1

	// 减库存
	key := fmt.Sprintf("goods:%d", goodsId)
	stock, err := Redis.HIncrBy(key, "stock", -number).Result()
	if err != nil {
		panic(err)
	}
	if stock < 0 {
		Redis.HIncrBy(key, "stock", number)
		return
	}

	// 下单
	var order = new(model.Order)
	order.UserId = rand.Intn(1000000)
	order.GoodsId = rand.Intn(1000000)
	order.Number = 1
	if err := db.Create(order).Error; err != nil {
		return
	}

	var orderMsg = new(model.OrderMsg)
	orderMsg.OrderId = order.Id
	orderMsg.GoodsId = order.GoodsId
	orderMsg.Number = order.Number
	orderMsg.UserId = order.UserId
	orderMsg.CreatedAt = order.CreatedAt

	jsonBytes, err := json.Marshal(orderMsg)
	if err != nil {
		log.Fatal(err)
	}

	// 发消息
	err = mq.Publish("order", jsonBytes)
	if err != nil {
		log.Panic(err)
	}
}

